from DBaseUtil import DBase
from M3u8ReaderUtil import M3u8Reader
import Common

class ADbase:
    
    CutOff_TABLE = "cutoff"
    
    adTrigger_FIELD = "adTrigger"
    
    def __init__(self, logFile):
        self.db = DBase("ad_list.db", self.scriptCreateAdCutoffList())
        self.logger = logFile
        self.cutoffFileList = []
        
        
    def scriptCreateAdCutoffList(self):
        return "CREATE TABLE IF NOT EXISTS " + ADbase.CutOff_TABLE + " ( \
        " + ADbase.adTrigger_FIELD + " TEXT PRIMARY KEY);"
        
    def PopulateAds(self):
        # populate if not exists
        #Get latest m3u8
        # Get First TS
        #insert ad-triggers at 100 places, at intervals of 4 each 
        
        # finding if ad already exists
        self.db.cursor.execute("SELECT " + ADbase.adTrigger_FIELD + "\
        FROM " + ADbase.CutOff_TABLE)
        self.db.row = self.db.cursor.fetchone()
        adExists = True if (self.db.row is not None) else False
        self.logger.logthis("Ad already exists: " + str(adExists), Common.Logger.GET_Request)
        
        if not adExists:
            m3u8Name = "01.m3u8"
            m3u8Name = Common.GetLatest(m3u8Name)
            tempM3u8 = M3u8Reader(m3u8Name).getM3u8()
            lastRequest = tempM3u8.GetFirstTS()
            lastRequest = Common.NextAvailableRequest(lastRequest)
            
            splitname = lastRequest.split("-")
            base = splitname[2].rstrip(".ts")
            base = int(base)
            self.logger.logthis("Base: " + str(base), Common.Logger.GET_Request)
            for i in range(10, 200, 10):
                newFile = lastRequest.replace(str(base), str(base+i))
                self.logger.logthis("inserting: " + newFile, Common.Logger.GET_Request)
                self.cutoffFileList.append(newFile)
#            self.logger.logthis("Cutoff-list: " + str(self.cutoffFileList), Common.Logger.GET_Request)
            
            #insert cutofflist into DB
            for item in self.cutoffFileList:
                self.db.cursor.execute("INSERT INTO " + ADbase.CutOff_TABLE + " \
                (" + ADbase.adTrigger_FIELD + ") VALUES (?)", [item])
#            self.db.cursor.executemany("INSERT INTO " + ADbase.CutOff_TABLE + " \
#            (" + ADbase.adTrigger_FIELD + ") VALUES (%s)", self.cutoffFileList)

    def GetAdList(self):
        self.db.cursor.execute("SELECT " + ADbase.adTrigger_FIELD + "\
         FROM " + ADbase.CutOff_TABLE)
        rows = self.db.cursor.fetchall()
        result = []
        for item in rows:
            result.append(item[0])
        
        return result
    
    def DeleteDB(self):
        Common.DeleteFile(self.db.GetFileName(), True)
    
